package org.jeecg.modules.water.controller;

import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.water.entity.LwgyJointWaterCmd;
import org.jeecg.modules.water.entity.LwgyJointWaterConfiguration;
import org.jeecg.modules.water.service.ILwgyJointWaterCmdService;
import org.jeecg.modules.water.service.ILwgyJointWaterConfigurationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.water.service.ILwgyRelaxConnectionService;
import org.jeecg.modules.water.service.ILwgyRelaxNbConnectionService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 设备管理
 * @Author: jeecg-boot
 * @Date:   2024-01-25
 * @Version: V1.0
 */
@Api(tags="设备管理")
@RestController
@RequestMapping("/device/lwgyJointWaterConfiguration")
@Slf4j
public class LwgyJointWaterConfigurationController extends JeecgController<LwgyJointWaterConfiguration, ILwgyJointWaterConfigurationService> {
	@Autowired
	private ILwgyJointWaterConfigurationService lwgyJointWaterConfigurationService;
	@Autowired
	private ILwgyRelaxNbConnectionService lwgyRelaxNbConnectionService;

	@Autowired
	private ILwgyRelaxConnectionService lwgyRelaxConnectionService;
	@Autowired
	private ILwgyJointWaterCmdService lwgyJointWaterCmdService;

	/**
	 * 分页列表查询
	 *
	 * @param lwgyJointWaterConfiguration
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "设备管理-分页列表查询")
	@ApiOperation(value="设备管理-分页列表查询", notes="设备管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<LwgyJointWaterConfiguration>> queryPageList(LwgyJointWaterConfiguration lwgyJointWaterConfiguration,
																	@RequestParam(name="treeId",required = false) String treeId,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		System.out.println("treeId:"+treeId);
		System.out.println("getRoomId:"+lwgyJointWaterConfiguration.getRoomId());
		QueryWrapper<LwgyJointWaterConfiguration> queryWrapper = QueryGenerator.initQueryWrapper(lwgyJointWaterConfiguration, req.getParameterMap());
		/*queryWrapper.or().eq( "campus_id", treeId)
		.or().eq(  "building_id", treeId)
		.or().eq( "unit_id",treeId)
		.or().eq(  "layer_id", treeId)
		.or().eq(  "room_id",treeId);

*/		if(oConvertUtils.isNotEmpty(treeId)) {
			queryWrapper.and(wrapper -> wrapper.eq("campus_id", treeId)
					.or().eq("building_id", treeId)
					.or().eq("unit_id", treeId)
					.or().eq("layer_id", treeId)
					.or().eq("room_id", treeId));
		}
		Page<LwgyJointWaterConfiguration> page = new Page<LwgyJointWaterConfiguration>(pageNo, pageSize);
		//IPage<LwgyJointWaterConfiguration> pageList = lwgyJointWaterConfigurationService.page(page, queryWrapper);
		IPage<LwgyJointWaterConfiguration> pageList = lwgyJointWaterConfigurationService.queryWaterDeviceList(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param lwgyJointWaterConfiguration
	 * @return
	 */
	@AutoLog(value = "设备管理-添加")
	@ApiOperation(value="设备管理-添加", notes="设备管理-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {
		lwgyJointWaterConfigurationService.save(lwgyJointWaterConfiguration);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param lwgyJointWaterConfiguration
	 * @return
	 */
	@AutoLog(value = "设备管理-编辑")
	@ApiOperation(value="设备管理-编辑", notes="设备管理-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {
		lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备管理-通过id删除")
	@ApiOperation(value="设备管理-通过id删除", notes="设备管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		lwgyJointWaterConfigurationService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "设备管理-批量删除")
	@ApiOperation(value="设备管理-批量删除", notes="设备管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.lwgyJointWaterConfigurationService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设备管理-通过id查询")
	@ApiOperation(value="设备管理-通过id查询", notes="设备管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		LwgyJointWaterConfiguration lwgyJointWaterConfiguration = lwgyJointWaterConfigurationService.getById(id);
		if(lwgyJointWaterConfiguration==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(lwgyJointWaterConfiguration);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param lwgyJointWaterConfiguration
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {
        return super.exportXls(request, lwgyJointWaterConfiguration, LwgyJointWaterConfiguration.class, "设备管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LwgyJointWaterConfiguration.class);
    }


	 /**
	  * 通过nb设备号查询设备信息（设备校验）
	  *
	  * @param lwgyJointWaterConfiguration
	  * @return
	  */
	 @AutoLog(value = "轻松设备管理-通过nb设备号查询设备信息")
	 @ApiOperation(value="轻松设备管理-通过nb设备号查询设备信息", notes="轻松设备管理-通过nb设备号查询设备信息")
	 @PutMapping(value = "/queryByDeviceNum")
	 public Result<?> queryByDeviceNum( @RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {

		 String deviceInfo= lwgyRelaxNbConnectionService.checkdeviceinfo(lwgyJointWaterConfiguration);

		 if(deviceInfo!=null && oConvertUtils.isNotEmpty(deviceInfo)){
			 JSONObject resultjson = JSONObject.parseObject(deviceInfo);
			 System.out.println("resultjson"+resultjson);
			 String code = resultjson.getString("code");
			 if("0".equals(code)){
				 JSONArray data = resultjson.getJSONArray("data");
				 if(data.size()>0){
					 for (int i = 0; i < data.size(); i++) {
						 JSONObject dataObject = data.getJSONObject(i);

						 String battery = dataObject.getString("battery"); // battery:”0”, //电池状态
						 String number = dataObject.getString("code");  // code:”201309260213”, //表号
						 String ispid = dataObject.getString("ispid"); // ispid:”7003525785”,  //设备通讯码，运营商平台生成的
						 String valvestate = dataObject.getString("valvestate");   // valvestate:”0”, //阀门状态 02未知 00开 01关 10无阀 11异常
						 String signalstrength = dataObject.getString("signalstrength");// signalstrength:”23”, //信号
						 String readperiod = dataObject.getString("readperiod"); // readperiod:”48” //周期半小时一个单位，48为24小时
						 String reversenum = dataObject.getString("reversenum");   // reversenum:”0.1”//反向读数

						 System.out.println("电池状态："+battery);
						 if(
						 	 lwgyJointWaterConfiguration.getDeviceNumber().equals(number)){
							 lwgyJointWaterConfiguration.setBatteryStatus(battery);
							 lwgyJointWaterConfiguration.setCommunicationCode(ispid);
							 lwgyJointWaterConfiguration.setValveStatus(valvestate);
							 lwgyJointWaterConfiguration.setSignalstrength(signalstrength);
							 lwgyJointWaterConfiguration.setCycle(readperiod);
							 lwgyJointWaterConfiguration.setReverseReading(reversenum);

							 lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);

							 return  Result.OK();
						 }
					 }
				 }else{
					 return Result.error("没有获取到设备信息");
				 }

			 }else{
				 String msg = resultjson.getString("msg");
				 return Result.error(msg);
			 }

		 }else{
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(lwgyJointWaterConfiguration);
	 }
	 @AutoLog(value = "轻松设备管理-nb表关阀")
	 @ApiOperation(value="轻松设备管理-nb表关阀", notes="轻松设备管理-nb表关阀")
	 @PutMapping(value = "/sendclose")
	 public Result<?> sendclose( @RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration){
	 	//先生成一条开关阀记录，id	做参数传入轻松
		 LwgyJointWaterCmd cmd = new LwgyJointWaterCmd();
		 long currentTimestamp = System.currentTimeMillis();
		 cmd.setId(String.valueOf(currentTimestamp));
		 cmd.setIspid(lwgyJointWaterConfiguration.getCommunicationCode());
		 cmd.setType("2");//1、开阀 2、关阀
		 cmd.setOperationalState("0");
		 //开关成功后保存记录
		 String  result= lwgyRelaxNbConnectionService.sendCmd(cmd);
		 if(result!=null && oConvertUtils.isNotEmpty(result)){
			 JSONObject resultjson = JSONObject.parseObject(result);
			 System.out.println("resultjson"+resultjson);
			 String code = resultjson.getString("code");
			 String data1 = resultjson.getString("data");
			 if("0".equals(code) && "1".equals(data1)){
				 cmd.setOperationalState("1");
				 lwgyJointWaterConfiguration.setValveStatus("CLOSE");
				 lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);
			 }
		 }

		 lwgyJointWaterCmdService.save(cmd);
	 	return Result.OK();
	 }

	 @AutoLog(value = "轻松设备管理-nb表开阀")
	 @ApiOperation(value="轻松设备管理-nb表开阀", notes="轻松设备管理-nb表开阀")
	 @PutMapping(value = "/sendopen")
	 public Result<?> sendopen( @RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {
		 //先生成一条开关阀记录，id	做参数传入轻松
		 LwgyJointWaterCmd cmd = new LwgyJointWaterCmd();
		 long currentTimestamp = System.currentTimeMillis();
		 cmd.setId(String.valueOf(currentTimestamp));
		 cmd.setIspid(lwgyJointWaterConfiguration.getCommunicationCode());
		 cmd.setType("1");//1、开阀 2、关阀
		 cmd.setOperationalState("0");
		 //开关成功后保存记录
		 String result = lwgyRelaxNbConnectionService.sendCmd(cmd);//resultjson{"msg":"处理成功","code":0,"data":1}
		 if (result != null && oConvertUtils.isNotEmpty(result)) {
			 JSONObject resultjson = JSONObject.parseObject(result);
			 System.out.println("resultjson" + resultjson);
			 String code = resultjson.getString("code");
			 String data1 = resultjson.getString("data");
			 if ("0".equals(code) && "1".equals(data1)) {
				 cmd.setOperationalState("1");
				 lwgyJointWaterConfiguration.setValveStatus("OPEN");
				 lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);
			 }
		 }

		 lwgyJointWaterCmdService.save(cmd);
		 return Result.OK();
	 }



	 @AutoLog(value = "轻松设备管理-通过Lora设备号查询设备信息")
	 @ApiOperation(value="轻松设备管理-通过Lora设备号查询设备信息", notes="轻松设备管理-通过Lora设备号查询设备信息")
	 @PutMapping(value = "/queryLoraByDeviceNum")
	 public Result<?> queryLoraByDeviceNum( @RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {

		 String deviceInfo= lwgyRelaxConnectionService.ReadDeviceInformation(lwgyJointWaterConfiguration);
//{"code":0,"msg":null,"data":{"extendDict":{"deviceTypeCode":"SBHB","deviceClock":"2024-01-28 09:11:26","updateTime":"2024-03-20 02:23:15","deviceCode":"00005386","deviceRSSI":65,"deviceBuyTimes":2,"deviceVoltage":3.54,"deviceStatus":"","valveStatus":1,"feeStatus":0,"voltageStatus":0,"deviceCurrentData":0,"deviceLastData":75,"deviceSettleDay":31,"deviceSettleDayData":75,"deviceBalance":1990,"deviceTotalData":100,"externalCode":null,"deviceUserName":"张三","deviceAddress":"山东省/泰安市/泰山区/金凤嘉苑/一号楼/101"},"responseCode":0,"responseInfo":"读取正常"}}
		 if(deviceInfo!=null && oConvertUtils.isNotEmpty(deviceInfo)){
			 JSONObject resultjson = JSONObject.parseObject(deviceInfo);
			 System.out.println("resultjson"+resultjson);
			 String code = resultjson.getString("code");
			 if("0".equals(code)){
				 JSONObject data = resultjson.getJSONObject("data");
				 JSONObject extendDict = data.getJSONObject("extendDict");
				 String battery = extendDict.getString("voltageStatus"); // battery:”0”, //电池状态
				 String number = extendDict.getString("deviceCode");// code:”201309260213”, //表号
				 String ispid = extendDict.getString("deviceCode");// ispid:”7003525785”,  //设备通讯码
				 String valvestate = extendDict.getString("valveStatus"); //int 0 无阀控 1开-合 2 关-断 3 异常 4 漏气 5 比率开阀
				 String signalstrength = extendDict.getString("deviceRSSI");// signalstrength:”23”, //信号
				 System.out.println("--------:"+signalstrength);
				 if(lwgyJointWaterConfiguration.getDeviceNumber().equals(number)){
					 lwgyJointWaterConfiguration.setBatteryStatus(battery);
					 lwgyJointWaterConfiguration.setCommunicationCode(ispid);
					 lwgyJointWaterConfiguration.setValveStatus(valvestate);
					 lwgyJointWaterConfiguration.setSignalstrength(signalstrength);

					 lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);

					 return  Result.OK();
				 }
				 return Result.error("未找到对应数据");
			 }else{
				 String msg = resultjson.getString("msg");
				 return Result.error(msg);
			 }

		 }else{
			 return Result.error("未找到对应数据");
		 }

	 }


	 @AutoLog(value = "轻松设备管理-lora表关阀")
	 @ApiOperation(value="轻松设备管理-lora表关阀", notes="轻松设备管理-lora表关阀")
	 @PutMapping(value = "/sendloraclose")
	 public Result<?> sendloraclose( @RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration){
		 //先生成一条开关阀记录，id	做参数传入轻松
		 LwgyJointWaterCmd cmd = new LwgyJointWaterCmd();
		 long currentTimestamp = System.currentTimeMillis();
		 cmd.setId(String.valueOf(currentTimestamp));
		 cmd.setIspid(lwgyJointWaterConfiguration.getCommunicationCode());
		 cmd.setType("2");//1、开阀 2、关阀
		 cmd.setOperationalState("0");
		 //开关成功后保存记录
		// String  result= lwgyRelaxNbConnectionService.sendCmd(cmd);
		 String  result= lwgyRelaxConnectionService.OpenOrCloseDevice(cmd);
		 if(result!=null && oConvertUtils.isNotEmpty(result)){
			 JSONObject resultjson = JSONObject.parseObject(result);
			 System.out.println("resultjson"+resultjson);
			 String code = resultjson.getString("code");
			 String msg = resultjson.getString("msg");
			 if("0".equals(code)){
				 cmd.setOperationalState("1");
				 lwgyJointWaterConfiguration.setValveStatus("2");
				 lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);

			 }else{
				 return  Result.error(msg);
			 }
		 }
		 lwgyJointWaterCmdService.save(cmd);
		 return Result.OK();
	 }



	/*	 if(result!=null && oConvertUtils.isNotEmpty(result)){
			 JSONObject resultjson = JSONObject.parseObject(result);
			 System.out.println("resultjson"+resultjson);
			 String code = resultjson.getString("code");
			 String data1 = resultjson.getString("data");
			 if("0".equals(code) && "1".equals(data1)){
				 cmd.setOperationalState("1");
				 lwgyJointWaterConfiguration.setValveStatus("CLOSE");
				 lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);
			 }
		 }*/




	 @AutoLog(value = "轻松设备管理-lora表开阀")
	 @ApiOperation(value="轻松设备管理-lora表开阀", notes="轻松设备管理-lora表开阀")
	 @PutMapping(value = "/sendloraopen")
	 public Result<?> sendloraopen( @RequestBody LwgyJointWaterConfiguration lwgyJointWaterConfiguration) {
		 //先生成一条开关阀记录，id	做参数传入轻松
		 LwgyJointWaterCmd cmd = new LwgyJointWaterCmd();
		 long currentTimestamp = System.currentTimeMillis();
		 cmd.setId(String.valueOf(currentTimestamp));
		 cmd.setIspid(lwgyJointWaterConfiguration.getCommunicationCode());
		 cmd.setType("1");//1、开阀 2、关阀
		 cmd.setOperationalState("0");
		 //开关成功后保存记录
		 String  result= lwgyRelaxConnectionService.OpenOrCloseDevice(cmd);
		 if(result!=null && oConvertUtils.isNotEmpty(result)){
			 JSONObject resultjson = JSONObject.parseObject(result);
			 System.out.println("resultjson"+resultjson);
			 String code = resultjson.getString("code");
			 String msg = resultjson.getString("msg");
			 if("0".equals(code)){
				 cmd.setOperationalState("1");
				 lwgyJointWaterConfiguration.setValveStatus("1");
				 lwgyJointWaterConfigurationService.updateById(lwgyJointWaterConfiguration);

			 }else{
				 return  Result.error(msg);
			 }
		 }
		 lwgyJointWaterCmdService.save(cmd);
		 return Result.OK();
	 }

 }
